package com.thinkgem.jeesite.modules.fantasy.common.scheduler;

import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.thinkgem.jeesite.modules.fantasy.entity.CityMap;
import com.thinkgem.jeesite.modules.fantasy.entity.ItemType;
import com.thinkgem.jeesite.modules.fantasy.utils.RandomUtils;

/**
* <p>Title: RandomItems</p>
* <p>Description: 道具随机发送类，使用ScheduledExecutorService执行</p>
* <p>Company: www.huanzhidadi.xin</p>
* @author wanghui
* @date 2017年12月3日
*/
public class RandomItems implements Runnable {
	/**
	 * 日志对象
	 */
	protected Logger logger = LoggerFactory.getLogger(getClass());
	public Map<String, CityMap> cities = new HashMap<String, CityMap>();
	public Map<String, ItemType> itemTypes = new HashMap<String, ItemType>();
	public Map<String, ItemType[]> ranItems = new HashMap<String, ItemType[]>();

	public RandomItems(Map<String, CityMap> cities, Map<String, ItemType> itemTypes, Map<String, ItemType[]> ranItems) {
		this.cities = cities;
		this.itemTypes = itemTypes;
		this.ranItems = ranItems;
	}
	
	@Override
	public void run() {
		if (!ranItems.isEmpty()) {
			logger.info("清理现有道具开始。");
			ranItems.clear();

			logger.info("清理现有道具结束。{}", ranItems.isEmpty());
		}
		randomItem();
	}
	/**
	* <p>Title: randomItem</p>
	* <p>Description: 随机发送道具到各个地点</p>
	*/
	public void randomItem() {

		logger.info("随机发送道具开始。");
		logger.debug("cities.size() = {}", cities.size());
		logger.debug("itemTypes.size() = {}", itemTypes.size());

		int count = cities.size();
		while (count > 0) {//有多少地点就初始化多少个道具
			count--;
			logger.debug("第{}次", (cities.size() - count));
			CityMap cityMap = RandomUtils.getRandomValueFromMap(cities);
			logger.debug("randCity = {}， id = {}", cityMap.getPlacename(), cityMap.getId());
			ItemType itemType = RandomUtils.getRandomValueFromMap(itemTypes);
			logger.debug("randItem = {}", itemType.getName());
			//使用数组存储数据，实现在页面的固定格子显示道具。
			if(!ranItems.containsKey(cityMap.getId())){//如果当前地点没有初始化过道具，就生成一个新的道具数组
				ranItems.put(cityMap.getId(), new ItemType[30]);
			}
			ItemType[] items = ranItems.get(cityMap.getId());//获取该地点上的道具数组
			for (int i=0; i<items.length; i++) {
				//循环该地点的道具数组，在第一个为空的格子中生成一个新的道具，跳出循环
				if (items[i] == null) {
					items[i] = itemTypes.get(itemType.getId());
					break;
				}
			}
		}
		logger.info("随机发送道具结束。");
	}
}
